package com.peter.core;

import org.apache.commons.beanutils.BeanUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by zmy on 2018/4/4.
 */
public class BaseDao {
    public int update(String sql, Object... params) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        int update = 0;
        try {
            // 获取链接
            connection = JdbcUtils.getConnection();
            //创建执行命令的stmt对象
            pstmt = connection.prepareStatement(sql);
            // 通过元数据得到占位符参数
            int count = pstmt.getParameterMetaData().getParameterCount();
            // 设置占位符参数
            if (params != null && params.length > 0) {
                for (int i = 0; i < count; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            // 执行更新
            update = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 释放资源
            JdbcUtils.release(connection, pstmt, null);
        }
        return update;
    }

    public <T> List<T> query(String sql, Class<T> clazz, Object... params) {
        Connection connection = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            // 创建list集合
            List<T> list = new ArrayList<>();
            // 获取连接
            connection = JdbcUtils.getConnection();
            pstmt = connection.prepareStatement(sql);
            // 获取元信息
            int count = pstmt.getParameterMetaData().getParameterCount();
            // 设置占位符参数值
            if (params != null && params.length > 0) {
                for (int i = 0; i < count; i++) {
                    pstmt.setObject(i + 1, params[i]);
                }
            }
            // 获取查询结果集合
            rs = pstmt.executeQuery();

            // 获取结果集元数据
            ResultSetMetaData metaData = rs.getMetaData();
            // 获取列个数
            int columnCount = metaData.getColumnCount();
            // 遍历结果集
            while (rs.next()) {
                T t = clazz.newInstance();
                // 遍历一行的每一列
                for (int i = 0; i < columnCount; i++) {
                    // 获取列名
                    String columnName = metaData.getColumnName(i + 1);
                    Object objectValue = rs.getObject(columnName);
                    // 将属性拷贝到对象中
                    BeanUtils.copyProperty(t, columnName, objectValue);
                }
                list.add(t);
            }
            return list;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            JdbcUtils.release(connection, pstmt, rs);
        }
    }
}
